<?php


class OrderAction extends MemberAction {
    /*
    status 判断类型
    0.取消
    1.待付款
    2.已付款
    3.已发货
     4.完成订单
    5.退货
    6.退款中
    */
    /*
    thstatus 退货类型
    0.默认/取消
    1.申请退货
    2.审核通过，请提供客户信息
    3.用户已经提交物流信息，待退货
    4.后台确认，退货完成
    5.管理员确认收退货，
    */
    public function _initialize() {
        parent::_initialize();
        $this->db = D('Order');
    }
    //填写收货信息
    public function index() {
		$this->checkCancel();
        $state = $this->_get('state') > 0 ? $this->_get('state') : 0;
        $saleDb = M('Sale');
        if ($state == 2) {
            //已付款,待发货
            $data = $this->db->_list("status=2 and shipping_status in(0) and member_id={$this->memberInfo['id']} and site_id=" . __SITEID__, 'id desc', 5);
        }else if ($state == 3){
            //已发货,待收货
            $data = $this->db->_list("shipping_status in(1,2) and member_id={$this->memberInfo['id']} and site_id=" . __SITEID__, 'id desc', 5);
        }elseif ($state == 7) {
            //已取消
            $data = $this->db->_list("status=0 and member_id={$this->memberInfo['id']} and site_id=" . __SITEID__, 'id desc', 5);
        } elseif ($state == 1) {
            //待支付
            $data = $this->db->_list("status=1 and member_id={$this->memberInfo['id']} and site_id=" . __SITEID__, 'id desc', 5);
        } elseif ($state == 6) {
            //已确认，完成
            //$sql = $saleDb -> where(array('member_id' => $this->memberInfo['id'], 'confirm' => 1)) -> Field('order_id as id') -> buildSql();
            //$data = $this->db->_list("status=4 and id in(".$sql.") and site_id=".__SITEID__,'id desc',5);
            $data = $this->db->_list("shipping_status=4 and member_id={$this->memberInfo['id']} and site_id=" . __SITEID__, 'id desc', 5);
        } else {
            //全部
            $data = $this->db->_list("member_id={$this->memberInfo['id']} and site_id=" . __SITEID__, 'id desc', 5);
        }
        //查询订单详情
        $list = $data['list'];
        foreach ($list as $k => $v) {
            $list[$k]['sale'] = $saleDb->alias('s')->join("left join __PRODUCT__ as p on p.id=s.product_id")->where(array(
                's.order_id' => $v['id']
            ))-> Field('s.*') -> select();
        }
        $this->assign('state', $state);
        $this->assign('list', $list);
        $this->assign('pages', $data['pages']);
        $this->display();
    }
    //查看订单详情
    public function read() {
        if ($this->_get('id')) {
            $id = $this->_get("id");
            $saleDB = M("Sale");
            //查询一条订单数据
            $data = $this->db->where(array('id' => $id,'member_id' => $this->memberInfo['id']))->find();
            $supplier = $saleDB->where(array('order_id' => $id))->group('supplier_id')->select();
            $sale = array();
            foreach ($supplier as $k => $v) {
                $datas = $saleDB->alias('s')->join("left join __PRODUCT__ as p on p.id=s.product_id")->where(array(
                    's.order_id' => $id,'s.supplier_id' => $v['supplier_id']))->
                Field('s.img_url,s.title,p.id,p.autoconfirm, s.id as sale_id, s.thstatus, s.num,s.thnum, s.price,s.total, s.attr,s.logistics_num, s.confirm, s.endtime, s.status')->select();
                $sale[$v['supplier_id']]['product'] = $datas;
                $sale[$v['supplier_id']]['confirm'] = $datas[0]['confirm'];
                $sale[$v['supplier_id']]['logistics_num'] = $datas[0]['logistics_num'];
                $sale[$v['supplier_id']]['endtime'] = GetRTime($datas[0]['endtime']);
                $sale[$v['supplier_id']]['fee'] = D('Order_supplier')->where('order_id = '.$id.' and supplier_id = '.$v['supplier_id'])->getfield('shipping_fee');
              	$memberinfo=session('memberInfo');
				$time=time();
				if(($datas[0]['endtime']-$time)>0){
					$time_str=$this->left_time((int)$datas[0]['endtime'],$time,2);
				}else{
					$time_str='0天';
				}
				$sale[$v['supplier_id']]['endtime'] = $time_str;
                //七天自动确认收货
                if ($sale[$v['supplier_id']]['endtime'] == 0 && $sale[$v['supplier_id']]['confirm'] == 0) {
                    /*foreach($datas as $k=>$v){
                    $ret = $saleDB->where( array('id'=>$v['id']) )->save(array('confirm'=>1));
                    if($ret === false){continue;}
                    $openid = M('member')-> where(array('id'=>$this->memberInfo['id']))->getField('openid');
                    $text = '你的商品'.$v['title'].'已经自动确认收货';
                    sendWXMsg($openid, $text);
                    }*/
                }
            }
            //获取商品属性
            $attrvalDB = M('attr_val');
            foreach ($sale as $k => $v) {
                $attrval = explode(';', $v['attr']);
                $sale[$k]['attrmes'] = array();
                foreach ($attrval as $v) {
                    $mes = $attrvalDB->where(array(
                        'id' => $v
                    ))->find();
                    array_push($sale[$k]['attrmes'], $mes['val']);
                }
            }
			if(!$data){
			    $data=M('Order')->where(' id = '.$this->_get('id'))->find();
			}
            $this->assign('order', $data);
            $this->assign('goods', $sale);
            $this->display();
        } else {
            $this->error('参数错误，参数不能为空');
        }
    }
    //订单支付
    public function pay() {
        if ($this->_get('id')) {
            $id = $this->_get('id');
            $order = $this->db->where(array(
                'id' => $id
            ))->find();
            if (!$order) {
                $this->error('订单不存在！');
            }
            //跳转支付
            C('URL_MODEL', 0);
            redirect(U('Home/Payment/index', array(
                'id' => $order['id']
            ) , true, false, true));
        }
    }
	
	//计算相差的时间
	public function left_time($big, $small, $type=1){
    if ( strlen($big) != 10 || !is_int($big) ) return false;
    if ( strlen($small) != 10 || !is_int($small) ) return false;
    if ($big < $small) return false;

    $return = $re = abs($big-$small);

    $return = '';
    if ($d = floor($re/3600/24)) $return .= $d.'天';
    if ($h = floor(($re-3600*24*$d)/3600)) $return .= $h.'小时';
    if ( $type == 2 ) {
        $i = floor(($re-3600*24*$d-3600*$h)/60);
        $return .= $i.'分';
    }
    if ( $type == 3 ) {
        $i = floor(($re-3600*24*$d-3600*$h)/60);
        $return .= $i.'分';
        $s = floor($re-3600*24*$d-3600*$h-60*$i);
        $return .= $s.'秒';
    }

    return $return;
	}
	public function checkCancel(){
	    $data=D('Order')->
        where('status=1 and member_id ='.$this->memberInfo['id'].' and site_id = '.__SITEID__.' and  create_time <= UNIX_TIMESTAMP(date_sub(sysdate(),interval 30 MINUTE))')
            ->getfield('id',true);
	    foreach($data as $k =>$v){
	        D('Order')->where('id = '.$v)->save(array('status'=>0));
        }
	}
	
    //取消订单
    public function cancel() {
        $order_id = $this->_get('id') ? $this->_get('id', 'int') : 0;
        if ($order_id > 0) {
            //调用模型
            $ret = $this->db->cancel($order_id, __SITEID__);
            if ($ret !== false) {
                $this->success('成功取消订单!');
            } else {
                $this->error($this->db->getError());
            }
        } else {
            $this->error('参数错误！');
        }
    }
    public function selecttype() {
        $sale_id = $this->_get('sale_id');
       
        $saleDB = M('sale');
        $this->sale_goods = $saleDB->where(array(
            'id' => $sale_id
        ))->find();
        $this->product = M('Product')->where(array(
            'id' => $this->sale_goods['product_id']
        ))->find();
        $this->assign('thtype', $this->sale_goods['thtype']);
        $this->display();
    }
    /*
      换货处理
    */
    public function exchangegoods() {
		$OrderDB = D('Order');
		$SaleDB = D('Sale');
		$sale_id = $this->_get('sale_id');
		$sale_goods = $SaleDB->where(array(
            'id' => $sale_id
        ))->find();
		
		$this->product = M('Product')->where(array(
            'id' => $sale_goods['product_id']
        ))->find();
        $this->assign('sale_goods', $sale_goods);
		if (IS_POST) {
			/*退货数量和退货理由*/
			$remark = $this->_post('remark');
			$num = $this->_post('num');
			$thtype = $this->_post('thtype');
			$sale_id = $this->_post('sale_id', 'int') > 0 ? $this->_post('sale_id', 'int') : 0;
			if($sale_id == 0){
				$this->error('换货商品不存在！');return;
			}
			$thstatus = $SaleDB -> where(array('id' => $sale_id)) -> getField('thstatus');
			if($thstatus == 0){
				$thstatus = 1;
				$remark = '用户申请换货';
			}
			if($thstatus == 2){
				$thstatus = 3;
				$shipping['couriernumber'] = $this->_post('couriernumber');
                $shipping['courier'] = $this->_post('courier');
				$remark = '用户寄回商品，【'.$shipping['courier'].'】物流单号：'.$shipping['couriernumber'];
			}
			if($thstatus == 5){
				$thstatus = 4;
				$remark = '用户确认收货';
			}
		    $ret = $OrderDB -> updatethstatus($sale_goods['order_id'], $sale_id, __SITEID__, $thstatus, $num, $thtype, $remark, $shipping);
			if($ret){
				$this->success('操作成功');
			}else{
				$this->error($OrderDB -> errorinfo);
			}
		    return;
		}
		$returngoodsDB = D('Returngoods');
		$data = $returngoodsDB->_list(array(
			'sale_id' => $sale_goods['id']
		) , '', 10);
		$this->assign('list', $data['list']);
		$this->assign('pages', $data['pages']);
		$this->display();
		return;
		
    }
    /*
      退货处理
    */
    public function returngoods() {
		$OrderDB = D('Order');
		$SaleDB = D('Sale');
		$sale_id = $this->_get('sale_id');
		$sale_goods = $SaleDB->where(array(
            'id' => $sale_id
        ))->find();
		$this->product = M('Product')->where(array(
            'id' => $sale_goods['product_id']
        ))->find();
        $this->assign('sale_goods', $sale_goods);
		if (IS_POST) {
			/*退货数量和退货理由*/
			$remark = $this->_get('remark');
			$num = $this->_post('num');
			$thtype = $this->_post('thtype');
			$sale_id = $this->_post('sale_id', 'int') > 0 ? $this->_post('sale_id', 'int') : 0;
			$remark = '用户申请退货,退货信息：'.$remark;
			if($sale_id == 0){
				$this->error('退货商品不存在！');return;
			}
			$thstatus = $SaleDB -> where(array('id' => $sale_id)) -> getField('thstatus');
			if($thstatus == 0){
				$thstatus = 1;
				$remark = '用户申请退货,退货信息：'.$remark;
			}
			if($thstatus == 2){
				$thstatus = 3;
				$shipping['couriernumber'] = $this->_post('couriernumber');
                $shipping['courier'] = $this->_post('courier');
				$remark = '用户寄回商品，【'.$shipping['courier'].'】物流单号：'.$shipping['couriernumber'];
			}
	
		    $ret = $OrderDB -> updatethstatus($sale_goods['order_id'], $sale_id, __SITEID__, $thstatus, $num, $thtype, $remark, $shipping);
			if($ret){
				$this->success('操作成功');
			}else{
				$this->error($OrderDB -> errorinfo);
			}
		    return;
		}
		$returngoodsDB = D('Returngoods');
		$data = $returngoodsDB->_list(array(
			'sale_id' => $sale_goods['id']
		) , '', 10);
		$this->assign('list', $data['list']);
		$this->assign('pages', $data['pages']);
		$this->display();
		return;
    }
    //确认收货
    public function confirmgoods() {
        $sale = $this->_post('sale');
        $ordernumber = $this->_post('ordernumber');
        $saleDB = M('sale');
        if ($this->_post('sale')) {
            $mes = $saleDB->where(array(
                'id' => array(
                    'in',
                    implode(',', $sale)
                )
            ))->save(array(
                'confirm' => 1
            ));
            D('Order')->updateshipping($this->_post('order_id'), __SITEID__);
            $openid = M('member')->where(array(
                'id' => $this->memberInfo['id']
            ))->getField('openid');
            $text = '订单号:' . $ordernumber . '商品已送达，已签收！';
            sendWXMsg($openid, $text);
            $this->success('操作成功',U('confirm',array('id'=>$this->_post('order_id'))));
        } else {
            $this->error('操作失败');
        }
    }
    //订单退款
    public function refund() {
        $sale_id = intval($this->_get('sale_id')) > 0 ? intval($this->_get('sale_id')) : 0;
		if($sale_id == 0){
			$this->error('货品不存在！');
		}
		$saleDB = D('Sale');
		$sale = $saleDB -> where(array('id' => $sale_id, 'site_id' => __SITEID__)) -> find();
			
        $order = $this-> db -> where(array('id' => $sale['order_id'])) -> getField('total');
        if($sale['total'] > $order){
            $this->error('当前商品的交易方式不允许退款。');exit;
        }
        $data['thtype'] = 3;
        $map['id'] = $sale_id;
        $data['thstatus'] = 3;
        $data['thnum'] = $sale['num'];
        $ret = $saleDB -> where($map) -> data($data) -> save();
        //判断是否部分退货(单个供货商)
        $countReturn=D('Sale')->where('order_id = '.$sale['order_id'].' and supplier_id = '.$sale['supplier_id'].' and thstatus = 0')->count();
        if($countReturn){
            D('Order_supplier')->where('order_id ='.$sale['order_id'].' and supplier_id ='.$sale['supplier_id'])->save(array('service_status'=>3));
        }else{
            D('Order_supplier')->where('order_id ='.$sale['order_id'].' and supplier_id ='.$sale['supplier_id'])->save(array('service_status'=>4));
        }
        //判断是否部分退货
        $countReturn=D('Sale')->where('order_id = '.$sale['order_id'].' and thstatus = 0')->count();
        if($countReturn){
            D('Order')->where('id ='.$sale['order_id'])->save(array('service_status'=>3));
        }else{
            D('Order')->where('id ='.$sale['order_id'])->save(array('service_status'=>4));
        }

        if($ret !== false){
            $this->success('已经提交退款申请，等待审核……');
        }else{
            $this->error($saleDB -> getError());
        }
    }
    //完成订单
    public function confirm() {
        $ret = $this->db -> confirm($this->_get('id'), __SITEID__);
		if($ret){
			$this->success('操作成功！',U('Order/index'));
		}else{
			$this->error($this->db -> errorinfo);
		}
    }
	
	//创建充值订单
	public function savemoney(){
		if(isset($_POST['money'])){
			$orderDB = D('Order');
			
			$price = (float)$_POST['money'];
			if($price <= 0){
				$this->error('充值金额不能为零');exit;
			}
			if(!$this->memberInfo['id']){
				$this->error('用户登录超时，请重新登录后再充值！');exit;
			}
			$_POST['siteid'] = 0;
			$_POST['site_id'] = __SITEID__;
			$_POST['relate_id'] = __RELATEID__;
			$_POST['status'] = 1;//0.已取消 1.待支付 2.已支付
			$_POST['ordernumber'] = build_order_no();
			$_POST['create_time'] = time();
			$_POST['create_date'] = strtotime(date('Y-m-d'));
			$_POST['savemoney'] = 1;
			$_POST['total'] = $price;
			$_POST['member_id'] = $this->memberInfo['id']?$this->memberInfo['id']:0;
			$_POST['pay_type'] = isset($_POST['pay_type'])?$_POST['pay_type']:'';
			$_POST['Guestbook'] = '会员充值【'.$price.'】';
			$orderDB->create();
			$orderId = $orderDB->add();
			if($orderId){
				//写入订单明细
				$saledb = M('Sale');
				$saledata = array();
				$saledata['order_id'] = $orderId;
				$saledata['product_id'] = 0;
				$saledata['member_id'] = $this->memberInfo['id'];
				$saledata['num'] = 1;
				$saledata['site_id'] = __SITEID__;
				$saledata['price'] = $price;
				$saledata['aff_money'] = 0; 
				$saledata['total'] = $price;
				$saledata['attr'] = '';
				$saledata['title'] = '在线充值';
				$saledata['img_url'] = '/savemoney.jpg';
				$saledata['supplier_id'] = 0; 
				$saledata['code'] = $v['code'];
				$sale_id = $saledb -> data($saledata) -> add();
				if($_POST['total'] == 0){
					D('Order') -> upstate($_POST['ordernumber']); 
				    redirect(U('Payment/index', array('id' => $orderId)));
				}
				C('URL_MODEL',0);
				redirect(U('Home/Payment/index', array('id' => $orderId),true,false,true));
			}else{
				$this->error($orderDB->getError());
			}
		}else{
			
			//充值总额
			$this->total = (float)M('Member_account_log') -> where(array('member_id' => $this->memberInfo['id'], 'pdstate' => 901)) -> sum('changenum');
			
			
			$this->display();
		}
	}
}

